﻿using System;
using System.Net;

namespace WaitLess.Business.Data.Foursquare
{
    public static class ApiUriBuilder
    {
        public static UriBuilder BaseUrlV2()
        {
            return new UriBuilder("https://api.foursquare.com/v2");
        }

        public static UriBuilder VenuesV2Url()
        {
            return new UriBuilder("https://api.foursquare.com/v2/venues/search");
        }

        public static UriBuilder HereNowV2Url(string venueId)
        {
            var uri = string.Format("https://api.foursquare.com/v2/venues/{0}/herenow", venueId);

            return new UriBuilder(uri);
        }

        public static UriBuilder AddCheckInUrl()
        {
            return new UriBuilder("https://api.foursquare.com/v2/checkins/add");
        }

        public static UriBuilder WithVersion(this UriBuilder uri, string version)
        {
            uri.Query = AddQueryParameter(uri.Query, "v", version);
            return uri;
        }

        public static UriBuilder WithClientId(this UriBuilder uri, string clientId)
        {
            uri.Query = AddQueryParameter(uri.Query, "client_id", clientId);
            return uri;
        }

        public static UriBuilder WithClientSecret(this UriBuilder uri, string clientSecret)
        {
            uri.Query = AddQueryParameter(uri.Query, "client_secret", clientSecret);
            return uri;
        }

        public static UriBuilder WithAccessToken(this UriBuilder uri, string accessToken)
        {
            uri.Query = AddQueryParameter(uri.Query, "oauth_token", accessToken);
            return uri;
        }

        public static UriBuilder WithNear(this UriBuilder uri, string near)
        {
            uri.Query = AddQueryParameter(uri.Query, "near", near);
            return uri;
        }

        public static UriBuilder WithIntent(this UriBuilder uri, string intent)
        {
            uri.Query = AddQueryParameter(uri.Query, "intent", intent);
            return uri;
        }

        public static UriBuilder WithQuery(this UriBuilder uri, string query)
        {
            uri.Query = AddQueryParameter(uri.Query, "query", query);
            return uri;
        }

        public static UriBuilder WithAfterTimestamp(this UriBuilder uri, string secondsSinceEpoch)
        {
            uri.Query = AddQueryParameter(uri.Query, "afterTimestamp", secondsSinceEpoch);
            return uri;
        }

        private static string AddQueryParameter(string query, string key, string value)
        {
            var updatedQueryString = query.Substring(query.IndexOf("?") + 1);

            if (!string.IsNullOrWhiteSpace(updatedQueryString))
                updatedQueryString += "&";

            updatedQueryString += string.Format("{0}={1}", key, Uri.EscapeUriString(value));

            return updatedQueryString;
        }
    }
}
